package com.ukayunnuo.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ukayunnuo.domain.entity.UserInfo;
import com.ukayunnuo.service.UserInfoService;
import com.ukayunnuo.tdengine.mapper.UserInfoMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author yunnuo
 * @since 1.0.0
 */
@Slf4j
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Resource
    private UserInfoMapper userInfoMapper;

    @Resource
    private JdbcTemplate tdengineJdbcTemplate;


    @Override
    public List<UserInfo> selectByTs(Integer days) {
        return userInfoMapper.selectByDays(days);
    }

    @Override
    public UserInfo getByUserId(Long id) {
        return userInfoMapper.getByUserId(id);
    }

    @Override
    public boolean save(UserInfo userInfo) {
        return userInfoMapper.insertData(userInfo, "user_info_test_mybatis", "mybatis") > 0;
    }

    @Override
    public List<UserInfo> getByUserIdForTemplate(String id) {
        return tdengineJdbcTemplate.query("select * from user_info where user_id = ?",
                new BeanPropertyRowMapper<>(UserInfo.class),
                id);
    }

    @Override
    public Boolean saveForTemplate(UserInfo userInfo) {
        // 直接插入子表（已创建表情况）
        String sql = "INSERT INTO user_info_test1 (ts, user_id, user_name, create_time) VALUES (NOW, ?, ?, NOW)";
        // 插入数据是自动创表
//        String sql = "INSERT INTO user_info_test_jdbc_template USING user_info TAGS('jdbc_template') (ts, user_id, user_name, create_time) VALUES (?, ?, ?, NOW)";
        int saveFlag = tdengineJdbcTemplate.update(sql,
                Timestamp.valueOf(LocalDateTime.now()),
                userInfo.getUserId(),
                userInfo.getUserName());
        return saveFlag > 0;
    }

}
